﻿using Api.Shared.Model.Web.Login;
using Api.Shared.Sugar;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace FitterTest.Controllers
{
    [Route("api/private/v1/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class RolesController : ControllerBase
    {
        private readonly ISugarClientService helper;
        private readonly MySession mySession;

        public RolesController([FromKeyedServices(nameof(SqlName.sqlite))] ISugarClientService helper, MySession mySession)
        {
            this.helper = helper;
            this.mySession = mySession;
            //str = System.IO.File.ReadAllText("Roles.json");
        }

        private string str;

        [HttpGet]
        public async Task<IActionResult> GetRoles()
        {
            var rolesList = await this.helper.Db.Queryable<RolesItemNew>().ToListAsync();

            foreach (var role in rolesList)
            {
                var menuItemNews1 = await this.helper.Db
                    .Queryable<MenuItemNew>()
                    .Where(x => x.level == 1)
                    .ToListAsync();

                //一级菜单
                role.children = menuItemNews1
                    .Where(x => x.parentMenuItemId.Split(',').Contains(role.id.ToString()))
                    .ToList();
            }

            foreach (var role in rolesList)
            {
                foreach (var item1 in role.children)
                {
                    var menuItemNews2 = await this.helper.Db
                        .Queryable<MenuItemNew>()
                        .Where(x => x.level == 2)
                        .ToListAsync();

                    //二级菜单
                    item1.children = menuItemNews2
                        .Where(
                            x =>
                                x.parentMenuItemId.Split(',').Contains(item1.id.ToString())
                                && x.parentMenuItemId.Split(',').Contains(role.id.ToString())
                        )
                        .ToList();
                }
            }

            foreach (var role in rolesList)
            {
                foreach (MenuItemNew item1 in role.children)
                {
                    foreach (var item2 in item1.children)
                    {
                        var menuItemNews3 = await this.helper.Db
                            .Queryable<MenuItemNew>()
                            .Where(x => x.level == 3)
                            .ToListAsync();

                        item2.children = menuItemNews3
                            .Where(
                                x =>
                                    x.parentMenuItemId.Split(',').Contains(item2.id.ToString())
                                    && x.parentMenuItemId.Split(',').Contains(item1.id.ToString())
                                    && x.parentMenuItemId.Split(',').Contains(role.id.ToString())
                            )
                            .ToList();
                    }
                }
            }

            //List<RolesItem> rolesList = await this.helper.Db.Queryable<RolesItem>().Includes(x => x.children.Where(y => y.parentMenuItemId == 0).ToList()).ToListAsync();

            //foreach (var item in rolesList) //roles
            //{
            //    foreach (var item1 in item.children) //item1:一级菜单，已经找到
            //    {
            //        item1.children = await this.helper.Db.Queryable<MenuItem>()
            //            .Where(x => (x.parentMenuItemId == item1.id) && (x.rolesId == item1.rolesId))
            //            .ToListAsync();
            //    }
            //}

            //foreach (RolesItem item in rolesList)
            //{
            //    foreach (MenuItem item1 in item.children)//item1:一级菜单，
            //    {
            //        foreach (MenuItem item2 in item1.children) //item2:二级菜单
            //        {
            //            item2.children = await this.helper.Db.Queryable<MenuItem>()
            //                .Where(x => (x.parentMenuItemId == item2.id) && (x.rolesId == item2.rolesId))
            //                .ToListAsync();
            //        }
            //    }
            //}

            if (rolesList != null)
            {
                return Ok(rolesList);
            }
            return StatusCode(204, "Failed");
        }

        [HttpDelete("{roleId}/rights/{rightId}")]
        public IActionResult RemoveRightById(int roleId, int rightId)
        {
            return Ok();
        }

        [HttpPost("{roleId}")]
        public async Task<IActionResult> Rights(int roleId, [FromBody] int[] idStr)
        {
            if (roleId == 30)
            {
                return StatusCode(204, "超级管理员权限不能被修改!");
            }
            List<MenuItemNew> listAll = await this.helper.Db.Queryable<MenuItemNew>().ToListAsync();
            List<MenuItemNew> list = await this.helper.Db
                .Queryable<MenuItemNew>()
                .Where(x => idStr.Contains(x.id))
                .ToListAsync();

            // 假设 listAll 和 list 是 MenuItemNew 类型的 List 集合
            List<MenuItemNew> result = listAll
                .Where(all => !list.Any(sub => sub.id == all.id))
                .ToList();

            //增加权限
            foreach (var item in list)
            {
                if (item.parentMenuItemId.Split(',').Contains(roleId.ToString()))
                {
                    continue;
                }
                item.parentMenuItemId = item.parentMenuItemId + $",{roleId}";
            }
            int count1 = await this.helper.Db.Updateable<MenuItemNew>(list).ExecuteCommandAsync();

            //删除权限
            foreach (var item in result)
            {
                string[] newStr = { };
                string[] str = item.parentMenuItemId.Split(',');
                if (str.Contains(roleId.ToString()))
                {
                    newStr = item.parentMenuItemId
                        .Split(',')
                        .Where(x => x != roleId.ToString())
                        .ToArray();
                    item.parentMenuItemId = string.Join(",", newStr);
                }
            }

            int count2 = await this.helper.Db.Updateable<MenuItemNew>(result).ExecuteCommandAsync();

            if (count1 > 0 || count2 > 0)
            {
                return Ok();
            }
            return StatusCode(204, "Failed");
        }
    }
}
